"""WebSocket连接"""
import asyncio
import logging
from datetime import datetime
from aiowebsocket.converses import AioWebSocket


async def startup(uri):
    """开启websocket连接"""
    async with AioWebSocket(uri) as aws:
        # 1. 初始化连接
        converse = aws.manipulator
        # 2.需要向服务器发送的信息
        message = b'hello world'
        while True:
            # 3.向服务器发送信息，并打印输出信息的内容和时间
            await converse.send(message)
            print('{time}-client send: {message}'.format(time=datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                                                         message=message))
            # 4. 读取服务器推送客户端的信息，并打印输出信息的内容和时间
            mes = await converse.receive()
            print('{time}-client receive: {rec}'.format(time=datetime.now().strftime('%Y-%m-%d %H:%M:%S'), rec=mes))


if __name__ == '__main__':
    # 设定远程服务器地址
    remote = 'wss://echo.websocket.org'
    try:
        asyncio.get_event_loop().run_until_complete(startup(remote))
    except (Exception,) as e:
        print(e)
        logging.info('Quit.')
